<template>
  <!--  调整项匹配规则 -->
  <div>
    <el-row class="adjRule container">
      <!-- 左侧树 -->
      <el-col :span="6">
        <el-button @click="addOrEditFunc('1')">新增组</el-button>
        <vp-tree
          class="ie-tree-style"
          :vp-header="{show:true,text:'调整项匹配规则组',search:true,name:'ruleGroupName'}"
          :vp-title="'所有调整项匹配规则组'"
          :filter-node-method="filterNode"
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          ref="configTree"
          node-key="adjRuleGroup"
          :expand-on-click-node="false"
          check-on-click-node
          :render-content="rendertree"
        ></vp-tree>
      </el-col>
      <!-- 右侧表  -->
      <el-col :span="17" class="content-left" :offset="1">
        <adjRuleList ref="adjRuleList" :adjId="adjId" :countWay="countWay" :adjDef="adjDef" :adjRuleGroup="adjRuleGroup" :ruleGroupName="ruleGroupName"/>
        
      </el-col>
    </el-row>
    <!-- 调整项规则组新增、编辑弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="adjRuleGroupTitleName"
      :visible.sync="adjRuleGroupAddOrEdit"
      width="40%"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="120px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-col :span="15">
          <el-form-item label="规则组编号：" prop="adjRuleGroup">
            <el-input
              v-model.trim="saveForm.adjRuleGroup"
              maxlength="40"
              :disabled="operateType==2"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>（提示：只能输入字母、数字及下划线，最长字符数为40位）</el-form-item>
        </el-col>
        <el-col :span="15">
          <el-form-item label="规则组名称：" prop="ruleGroupName">
            <el-input
              v-model.trim="saveForm.ruleGroupName"
              maxlength="40"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>（提示：只能输入汉字、字母、数字及下划线，最长字符数100，一个汉字3位字符）</el-form-item>
        </el-col>
        <el-col :span="15">
          <el-form-item label="调整项定义：" prop="adjId">
            <el-select 
              v-model="saveForm.adjId" 
              placeholder="请选择"
              class="saveTempName2"
               ref="saveTempNameRef"
               @focus="setWidth"
              >
              <el-option
                :style="{width: optionwidth}"
                v-for="item in adjIds"
                :key="item.adjId"
                :label="item.adjName"
                :value="item.adjId"
                :title="item.adjName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer">
        <el-button @click="saveFunc">确 定</el-button>
        <el-button @click="adjRuleGroupAddOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { adjRule } from "@/api/index";
import adjRuleList from "./adjRule_list";
import moment from "moment";
export default {
  //定义数据
  data() {
    return {
      // 右侧树data
      treeData: [],
       optionwidth: "",
      defaultProps: {
        children: "children",
        label: "curveName"
      },
      adjRuleGroupTitleName: "",
      adjRuleGroupAddOrEdit: false,
      //规则组模板保存数据
      saveForm: {},
      //规则模板数据
      adjIds: [],
      //操作标识
      operateType: 1,
      //表单字段规则校验
      saveFormRules: {
        adjRuleGroup: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_]{1,40}/,
            message: "只可输入(1-40)位的英文字母、数字和下划线！",
            trigger: "blur"
          },
          { validator: this.adjRuleGroupValid, trigger: "blur" }
        ],
        ruleGroupName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { max: 100, message: "输入字符超过数据库设定最大长度", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
            message: "只可输入字母汉字数字_！",
            trigger: "blur"
          },
        ],
        adjId: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ]
      },
      //原规则组名称
      ruleGroupNameOld: "",
      adjId: "",
      adjRuleGroup: "",
      countWay:"",
      adjDef:{},

      //查询时默认条件
      searchForm: {
        page: 1,
        size: 15,
        adjCode: "",
        adjName: ""
      },
      total: 0,
      tableData: [],
      //弹窗标识
      ruleTemplateDi: false,
      //新增编辑弹出框名称
      titleName: "",
      adjCode: "",
      adjName: "",
      ruleGroupName: ""
    }
  },
  //组件引入
  components: {
    adjRuleList
  },
  //创建初始化
  created() {
    this.treeDataInit();
    this.adjIdsInit();
  },
  mounted() {
    
  },
  //监控数值变化
  watch: {

  },
  //运算
  computed: {
    
  },
  methods: {
    setWidth(){
        this.optionwidth = this.$refs.saveTempNameRef.$el.clientWidth+"px";
    },
    //树节点筛选执行的方法
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(obj) {
      // 单选处理
      if (obj.parentAdjRuleGroup != ""&&obj.parentAdjRuleGroup != "root") {
        this.adjId = obj.parentAdjRuleGroup;
        this.adjRuleGroup = obj.adjRuleGroup;
        this.ruleGroupName = obj.ruleGroupName;
        
        let obj2 = this.adjIds.filter(function (c) {
          if (c.adjId == obj.parentAdjRuleGroup) {
              return c
          }
      })
        this.countWay = obj2["0"].countWay;
        this.adjDef = obj2["0"];
        console.log(this.adjDef,"---this.adjDef--");

        setTimeout(()=>{
          this.$refs.adjRuleList.searchFunc()
        },10)
      }else{
        this.$message.warning("请选择规则组下的规则模板")
        this.adjId = ""
      }
    },
    rendertree(h, {data}) {
      return <span title={data.ruleGroupName}>
              <span style="margin-right:10px" on-click={()=>this.handleNodeClick(data)}>{this.stringFixed(data.ruleGroupName)}</span>
              <i style="margin-right:10px" class="el-icon-edit" on-click={()=>this.editRuleGroup(data)}></i>
              <i class="el-icon-delete" on-click={()=>this.deleteRuleGroup(data)}></i>
            </span>;
    },
     stringFixed(v){
      let str ="";
      if(v.length>20){
        str = v.substring(0,20)+'...'
      }else{
        str = v
      }
      return str
    },
    editRuleGroup(obj) {
      if(obj.parentAdjRuleGroup == null || obj.parentAdjRuleGroup == "") {
        return this.$message.warning("根节点不可编辑！");
      }  
        if(this.$refs.saveForm) {
          this.$refs.saveForm.resetFields();
        }
        this.ruleGroupNameOld = obj.ruleGroupName;
        this.operateType = "2";
        this.adjRuleGroupTitleName = "修改调整项规则组信息";
        this.adjRuleGroupAddOrEdit = true;
        
        let data = {
          adjRuleGroup:obj.adjRuleGroup
        }
        adjRule.toFormGroup(data).then(res => {
          if (res.code === 200) {
            this.saveForm = res.datas.adjRuleGroup;
            this.saveForm.adjId = res.datas.adjRuleGroup.adjustDefinition.adjId;

          }
        });
      
        
      
    },
    deleteRuleGroup(obj) {
      if (obj.parentAdjRuleGroup == null || obj.parentAdjRuleGroup == "") {
        return this.$message.warning("根节点不可删除!");
      } else {
        let data = {
          adjRuleGroup: obj.adjRuleGroup,
          adjId: obj.adjId
        }
        adjRule.checkUsingGroup(data).then(res => {
          if (res.code == 200) {
            if (res.data == "1") {
              return this.$message.warning("数据被情景管理引用，无法删除!");
            } else {
              this.$confirm("确定要删除数据吗", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              })
                .then(() => {
                  data = {
                    ids: [obj.adjRuleGroup]
                  }
                  adjRule.adjRuleGroupRemove(data).then(res => {
                    if (res.code == 200) {
                      this.$message.success("删除成功");
                      this.treeDataInit();
                    } else {
                      this.$message.error(res.message || "删除失败");
                    }
                  });
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消删除"
                  });
                });
            }
          }
        });
      }
    },
    treeDataInit() {
      this.adjId = ""
      adjRule.adjRuleGroupTree().then(res => {
        if (res.code === 200) {
          let list = res.datas;
          this.treeData = this.$listToTree("adjRuleGroup", "parentAdjRuleGroup", list);
        }
      });
      
    },
    addOrEditFunc(val) {
      if(this.$refs.saveForm) {
        this.$refs.saveForm.resetFields();
      }
      this.adjRuleGroupTitleName = "新增调整项规则组信息";
      this.adjRuleGroupAddOrEdit = true;
      this.operateType = val;
    },
    //规则组编号验证
    adjRuleGroupValid(rule, value, callback) {
      if(this.operateType == "1") {
        let data = {
          adjRuleGroup: value
        };
        adjRule.checkCode(data).then(res => {
          if (res.code === 200) {
            if(res.data == "1") {
              callback(new Error("编号已存在，无法使用！"));
            } else {
              callback();
            }
          }
        });
      } else {
        callback();
      }
    },
    //规则组名称验证
    ruleGroupNameValid(rule, value, callback) {
      if(this.operateType == "1"||(this.operateType == "2"&&this.ruleGroupNameOld != value)) {
        let data = {
          ruleGroupName: value
        };
        adjRule.checkNameUnique(data).then(res => {
          if (res.code === 200) {
            if(res.data == "1") {
              callback(new Error("此模板名称已存在，无法使用！"));
            } else {
              callback();
            }
          }
        });
      } else {
        callback();
      }
    },
    //模板类型初始化
    adjIdsInit () {
      let data = {
        templateType : "3"
      };
      adjRule.findAdjDefList(data).then(res => {
        if (res.code === 200) {
          this.adjIds = res.datas;
        }
      });
      
    },
    //规则组保存
    saveFunc () {
      this.$refs["saveForm"].validate(valid => {
        if(valid) {
          this.checkNameUnique()
        }
      });
    },
    saveFuncConfirm(){
      this.saveForm.adjustDefinition={
        adjId:this.saveForm.adjId
      }

      let data = {
            ...this.saveForm
          };
          adjRule.adjRuleGroupSave(data).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.adjRuleGroupAddOrEdit = false;
              this.treeDataInit();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
    },
    //规则组校验名称是否重复
    checkNameUnique(){
       if(this.operateType == "1"||(this.operateType == "2"&&this.ruleGroupNameOld != this.saveForm.ruleGroupName)) {
        let data = {
          ruleGroupName: this.saveForm.ruleGroupName
        };
        adjRule.checkNameUnique(data).then(res => {
          if (res.code === 200) {
            if(res.data == "1") {
              this.$message.warning("此模板名称已存在，无法使用")
            } else {
              this.saveFuncConfirm()
            }
          }
        });
      } else {
          this.saveFuncConfirm()
      }
    },
    //   点击行选中
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
          this.$refs.multipleTable.clearSelection()
      }
      this.$refs.multipleTable.toggleRowSelection(row, true)
    },
    //事件转换
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    //页码值改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    //当前页改变
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    }
  }
};
</script>


<style lang="scss" scoped>
 .el-table__header th {
  /deep/ .cell {
    white-space: nowrap !important;
  }
}

/deep/.el-dialog__body {
  max-height: 400px;
}
.tipMessage {
  line-height: 32px;
  margin-left: 5px;
  color: red;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500 !important;
  font-size: 12px !important;
}

.saveTempName2 {
  width: 100%;

  /deep/.el-select__tags-text {
  display: inline-block;//设置成行内块
  max-width: 65px;//设置最大宽度
  overflow: hidden;//隐藏滚动条
  text-overflow: ellipsis;//将超出部分用...代替
  white-space: nowrap;//段落中的文本不进行换行
}
 
/deep/.el-select .el-tag__close.el-icon-close {
  top: -7px;
}

}

</style>